package com.tingyu.blog.service;

import com.tingyu.blog.MyNotFoundException;
import com.tingyu.blog.dao.TagRepository;
import com.tingyu.blog.po.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class TagServiceImpl implements TagService {
    @Autowired
    private TagRepository tagRepository;


    @Transactional
    @Override
    /**
     * 添加标签
     * @param 标签对象(Tag tag)
     * @return 添加的标签对象
     */
    public Tag saveTag(Tag tag) {
        return tagRepository.save(tag);
    }

    @Transactional
    @Override
    /***
     * 查询一个标签
     * @param id
     */
    public Tag getOneTag(int id) {
        return tagRepository.getOne(id);
    }

    @Override
    public List<Tag> listTag() {
        return tagRepository.findAll();
    }

    /**
     * 根据标签中博客数量倒序后取前几条数据
     * @param size
     * @return
     */
    @Override
    public List<Tag> listTagTop(int size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"blogs.size");
        Pageable pageable = PageRequest.of(0,size,sort);
        return tagRepository.findTop(pageable);
    }

    @Override
    public List<Tag> listTag(String ids) {
        return tagRepository.findAllById(toList(ids));
    }

    /**
     * 字符串转int列表，供listTag(String ids) 使用
     * @param str
     * @return <Integer> list
     */
    public List<Integer> toList(String str){
        List<Integer> list = new ArrayList<>();
        if (!"".equals(str) && str != null){
            for (String s:str.split(",")) {
                list.add(Integer.valueOf(s));
            }
        }
        return list;
    }


    //通过名称获取一个标签对象
    @Override
    public Tag getOneTagByName(String name) {
        return tagRepository.findByName(name);
    }

    @Transactional
    @Override
    /**
     * 分页查询
     * @param pageable
     */
    public Page<Tag> listTag(Pageable pageable) {
        return tagRepository.findAll(pageable);
    }

    @Transactional
    @Override
    /**
     * 编辑、修改标签
     * @param id,tag对象
     * @return 返回修改、更新后的tag对象
     */
    public Tag editTag(int id, Tag tag) {
        Tag t = tagRepository.getOne(id);
        if (t == null){
            throw new MyNotFoundException("该标签不存在！");
        }
        BeanUtils.copyProperties(tag,t);   //用tag对象覆盖t对象
        return tagRepository.save(t);      //通过覆盖t对象内容已更新
    }

    @Transactional
    @Override
    /**
     * 删除分类
     * @param  int id
     */
    public void deleteTag(int id) {
        tagRepository.deleteById(id);
    }
}
